<script type="text/x-template" id="cc-json-edit-el">
    <div>
        <el-card class="box-card">
            <div class="jsoneditor-vue"></div>
        </el-card>
    </div>
</script>
<script>
    Vue.component('cc-json-edit-el', {
        template: '#cc-json-edit-el',
        data() {
            return {
                editor: null,
                error: false,
                json: this.value,
                internalChange: false,
                expandedModes: ["tree", "view", "form"],
            }
        },
        computed: {},
        props: {
            value: [String, Number, Object, Array],
            expandedOnStart: {
                type: Boolean,
                default: false
            },
            mode: {
                type: String,
                default: "code"
            },
            modes: {
                type: Array,
                default: function () {
                    return ["tree", "code", "form", "text", "view"];
                }
            },
            lang: {
                type: String,
                default: "zh"
            }
        },
        watch: {
            value: {
                immediate: true,
                async handler(val)
    {
        if (!this.internalChange) {
            this.setEditor(val);
            this.expandAll();
        }
    }
    ,
    deep: true
    }
    },
    mounted()
    {
        let self = this;

        let options = {
            mode: this.mode,
            modes: this.modes, // allowed modes
            onChange() {
                console.log("Json editor change");
                try {
                    let json = self.editor.get();
                    self.json = json;
                    self.internalChange = true;
                    self.$emit("input", json);
                    self.$nextTick(function () {
                        self.internalChange = false;
                    });
                } catch (e) {
                    self.$emit("has-error", e);
                }
            },
            onModeChange() {
                self.expandAll();
            }
        };

        this.editor = new JSONEditor(
                this.$el.querySelector(".jsoneditor-vue"),
                options,
                this.json
        );
    }
    ,
    methods: {
        expandAll()
        {
            if (
                    this.expandedOnStart &&
                    this.expandedModes.includes(this.editor.getMode())
            ) {
                this.editor.expandAll();
            }
        }
    ,
        setEditor(value)
        {
            if (this.editor) this.editor.set(value);
        }
    }
    })
</script>
